/*
 * CheckHubConnection.java
 *
 * Created on 23 de Dezembro de 2004, 14:52
 */

package ceirinhashls;
import ceirinhashls.util.IPHandle;
import java.io.*;
import java.net.Socket;
import java.text.MessageFormat;
import java.text.ParseException;
/**
 *
 * @author  botelhodaniel
 */
public class CheckHubConnection implements Runnable{
    private Socket socket;

	/**
	 * 
	 * @uml.property name="in"
	 * @uml.associationEnd multiplicity="(0 1)"
	 */
	private DCBufferedReader in;

	/**
	 * 
	 * @uml.property name="hub"
	 * @uml.associationEnd multiplicity="(1 1)"
	 */
	private DCHub hub;

	private DataOutputStream out;
	private MessageFormat message = new MessageFormat("$Lock {0} Pk={1}|");
    
    /** Creates a new instance of CheckHubConnection */
    public CheckHubConnection(DCHub hub) {
        this.hub = hub;
    }
    private void connectHub(String str) throws ParseException, IOException{
    	Object[] lock;
    	System.out.println(str);
    	lock = message.parse(str);
    	System.out.println(lock[0]);
        Encripter enc = new Encripter(lock[0]+"");
        
        out.write(("$Key "+enc.getKey()+"|").getBytes());
        
        out.write(("$MyINFO $ALL leinad -:: [away mode] ::- [\\] <++ V:0.403,M:A,H:1/0/0,S:4>$ $Cable$$28162729227$|").getBytes());
        //out.write("$BotINFO dssfgd|".getBytes()); <- 
        out.write(("$ValidateNick leinad|").getBytes());
        out.write(("$Version 1,0091|").getBytes());
        out.write(("$GetNickList|").getBytes());
        hub.setDescription("JA VERIFIKEI ESTE!!!");
        
        System.out.println(in.readLine());
    }
    public void run() {
        try{
            System.out.println("PING -> hub: "+hub.getAddress()+"("+IPHandle.removePort(hub.getAddress())+":"+hub.getPort()+")");
            socket = new Socket(IPHandle.removePort(hub.getAddress()),hub.getPort());
            //socket = new Socket("80.172.160.98",411);
            
            this.in = new DCBufferedReader(new InputStreamReader(this.socket.getInputStream()));
            this.out = new DataOutputStream(this.socket.getOutputStream());

            connectHub(in.readLine());
            
            
            /*System.out.println(in.readLine());
            if(in.readLine().startsWith("$Lock "))
            	hub.incTotalConnections();*/
            socket.close();
            System.out.println("Conseguiu...");
            
        } catch (IOException e) {
            e.printStackTrace();
            hub.incFaildConnections();
        } catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
    }
    
}
